import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/exam_model.dart';
import '../data/user_data.dart';
import 'package:flutter/foundation.dart';
import '../services/exam_service.dart';
import 'package:path_provider/path_provider.dart';
import 'package:excel/excel.dart';
import 'dart:io';
import '../models/question_model.dart';
import 'package:archive/archive_io.dart';
import 'student_service.dart';

class ExamStateService {
  // 保存考试状态的键前缀
  static const String _examStateKeyPrefix = 'exam_state_';
  // 保存考试结果的键前缀
  static const String _examResultKeyPrefix = 'exam_result_';

  // 获取考试状态键
  static String _getExamStateKey(String examId, String userId) {
    return '${_examStateKeyPrefix}${examId}_$userId';
  }

  // 获取考试结果键
  static String _getExamResultKey(String examId, String userId) {
    return '${_examResultKeyPrefix}${examId}_$userId';
  }

  // 获取用户的考试状态
  static Future<ExamState?> getExamState(String examId, String userId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = _getExamStateKey(examId, userId);
      
      final String? stateJson = prefs.getString(key);
      if (stateJson == null) {
        return null;
      }
      
      final Map<String, dynamic> stateMap = jsonDecode(stateJson);
      return ExamState.fromJson(stateMap);
    } catch (e) {
      debugPrint('获取考试状态失败: $e');
      return null;
    }
  }

  // 保存考试状态
  static Future<bool> saveExamState(ExamState state) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = _getExamStateKey(state.examId, state.userId);

      debugPrint('=== saveExamState ===');
      debugPrint('考试ID: ${state.examId}');
      debugPrint('用户ID: ${state.userId}');
      debugPrint('状态键: $key');
      debugPrint('状态: ${state.status}');
      debugPrint('剩余时间: ${state.remainingSeconds} 秒');
      debugPrint('答案数量: ${state.answers.length}');

      // 在保存前，先清理可能存在的重复状态
      await _cleanupDuplicateStatesForUser(state.examId, state.userId);

      final stateJson = jsonEncode(state.toJson());
      final result = await prefs.setString(key, stateJson);

      debugPrint('保存考试状态结果: ${result ? '✅ 成功' : '❌ 失败'}');

      // 验证保存结果
      if (result) {
        final verification = prefs.getString(key);
        if (verification != null) {
          debugPrint('✅ 状态保存验证成功');
        } else {
          debugPrint('❌ 状态保存验证失败');
          return false;
        }
      }

      return result;
    } catch (e) {
      debugPrint('❌ 保存考试状态失败: $e');
      return false;
    }
  }

  // 删除考试状态
  static Future<bool> removeExamState(String examId, String userId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = _getExamStateKey(examId, userId);

      debugPrint('=== 删除考试状态 ===');
      debugPrint('考试ID: $examId');
      debugPrint('用户ID: $userId');
      debugPrint('状态键: $key');

      // 检查状态是否存在
      final exists = prefs.containsKey(key);
      debugPrint('状态是否存在: $exists');

      if (!exists) {
        debugPrint('⚠️ 考试状态不存在，可能已经被删除');
        return true; // 如果不存在，认为删除成功
      }

      // 执行删除操作
      final result = await prefs.remove(key);
      debugPrint('删除操作结果: ${result ? '✅ 成功' : '❌ 失败'}');

      // 强制刷新SharedPreferences
      await prefs.reload();

      // 验证删除结果
      final stillExists = prefs.containsKey(key);
      if (stillExists) {
        debugPrint('❌ 警告: 删除后状态仍然存在，尝试强制删除');

        // 尝试多次删除
        for (int i = 0; i < 3; i++) {
          await prefs.remove(key);
          await prefs.reload();
          if (!prefs.containsKey(key)) {
            debugPrint('✅ 强制删除成功（第${i+1}次尝试）');
            return true;
          }
          await Future.delayed(Duration(milliseconds: 100));
        }

        debugPrint('❌ 强制删除失败，状态仍然存在');
        return false;
      }

      debugPrint('✅ 考试状态删除确认成功');
      return result;
    } catch (e) {
      debugPrint('❌ 删除考试状态失败: $e');
      return false;
    }
  }

  // 删除考试结果
  static Future<bool> removeExamResult(String examId, String userId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = _getExamResultKey(examId, userId);

      return await prefs.remove(key);
    } catch (e) {
      debugPrint('删除考试结果失败: $e');
      return false;
    }
  }

  // 保存考试结果
  static Future<bool> saveExamResult(ExamResult result) async {
    try {
      debugPrint('=== 保存考试结果 ===');
      debugPrint('考试ID: ${result.examId}');
      debugPrint('用户ID: ${result.userId}');
      debugPrint('总分: ${result.totalScore}');

      // 1. 保存到SharedPreferences（用于个人查看）
      final prefs = await SharedPreferences.getInstance();
      final key = _getExamResultKey(result.examId, result.userId);

      final resultJson = jsonEncode(result.toJson());
      final prefsSaved = await prefs.setString(key, resultJson);
      debugPrint('SharedPreferences保存: ${prefsSaved ? '成功' : '失败'}');

      // 2. 保存到ExamService（用于管理员查看）
      final serviceSaved = await ExamService.addExamResult(result);
      debugPrint('ExamService保存: ${serviceSaved ? '成功' : '失败'}');

      final overallSuccess = prefsSaved && serviceSaved;
      debugPrint('考试结果保存总体结果: ${overallSuccess ? '✅ 成功' : '❌ 失败'}');

      return overallSuccess;
    } catch (e) {
      debugPrint('保存考试结果失败: $e');
      return false;
    }
  }

  // 清理已完成考试的状态（管理员工具）
  static Future<int> cleanupCompletedExamStates() async {
    try {
      debugPrint('=== 开始清理已完成考试的状态 ===');
      final prefs = await SharedPreferences.getInstance();
      final allKeys = prefs.getKeys();

      // 筛选出所有考试状态键
      final stateKeys = allKeys.where((key) => key.startsWith(_examStateKeyPrefix)).toList();
      debugPrint('找到 ${stateKeys.length} 个考试状态键');

      int cleanedCount = 0;

      for (final key in stateKeys) {
        try {
          final String? stateJson = prefs.getString(key);
          if (stateJson != null) {
            final Map<String, dynamic> stateMap = jsonDecode(stateJson);
            final ExamState state = ExamState.fromJson(stateMap);

            // 检查是否已经有考试结果
            final hasPrefsResult = prefs.containsKey(_getExamResultKey(state.examId, state.userId));
            final hasServiceResult = ExamService.getUserExamResult(state.examId, state.userId) != null;

            if (hasPrefsResult || hasServiceResult) {
              debugPrint('清理已完成考试的状态: ${state.examId} - ${state.userId}');
              await prefs.remove(key);
              cleanedCount++;
            }
          }
        } catch (e) {
          debugPrint('处理状态键时出错: $key, 错误: $e');
        }
      }

      debugPrint('清理完成，共清理了 $cleanedCount 个已完成考试的状态');
      return cleanedCount;
    } catch (e) {
      debugPrint('清理已完成考试状态失败: $e');
      return 0;
    }
  }

  // 获取考试结果
  static Future<ExamResult?> getExamResult(String examId, String userId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = _getExamResultKey(examId, userId);
      
      final String? resultJson = prefs.getString(key);
      if (resultJson == null) {
        return null;
      }
      
      final Map<String, dynamic> resultMap = jsonDecode(resultJson);
      return ExamResult.fromJson(resultMap);
    } catch (e) {
      debugPrint('获取考试结果失败: $e');
      return null;
    }
  }

  // 获取当前用户的考试状态
  static Future<ExamState?> getCurrentUserExamState(String examId) async {
    final currentUser = UserData.currentUser;
    if (currentUser == null) {
      return null;
    }
    
    return await getExamState(examId, currentUser.id);
  }

  // 获取当前用户的考试结果
  static Future<ExamResult?> getCurrentUserExamResult(String examId) async {
    final currentUser = UserData.currentUser;
    if (currentUser == null) {
      return null;
    }

    // 首先从SharedPreferences获取
    final prefsResult = await getExamResult(examId, currentUser.id);
    if (prefsResult != null) {
      debugPrint('从SharedPreferences找到考试结果');
      return prefsResult;
    }

    // 如果SharedPreferences中没有，从ExamService获取
    final serviceResult = ExamService.getUserExamResult(examId, currentUser.id);
    if (serviceResult != null) {
      debugPrint('从ExamService找到考试结果');
      return serviceResult;
    }

    debugPrint('未找到考试结果');
    return null;
  }

  // 获取考试状态
  static Future<ExamStatus> getExamStatus(String examId, {String? userId}) async {
    final String userIdToUse = userId ?? UserData.currentUser?.id ?? '';
    if (userIdToUse.isEmpty) {
      return ExamStatus.notStarted;
    }
    
    // 先检查是否有考试结果
    final result = await getExamResult(examId, userIdToUse);
    if (result != null) {
      return ExamStatus.completed;
    }
    
    // 再检查是否有进行中的考试
    final state = await getExamState(examId, userIdToUse);
    if (state != null) {
      return state.status;
    }
    
    return ExamStatus.notStarted;
  }

  // 自动保存考试状态（定期调用）
  static Future<bool> autoSaveExamState(String examId, Map<String, dynamic> answers, int remainingSeconds) async {
    final currentUser = UserData.currentUser;
    if (currentUser == null) {
      debugPrint('❌ autoSaveExamState: 当前用户为空');
      return false;
    }

    debugPrint('=== autoSaveExamState ===');
    debugPrint('考试ID: $examId');
    debugPrint('用户ID: ${currentUser.id}');
    debugPrint('剩余时间: $remainingSeconds 秒');
    debugPrint('当前答案数量: ${answers.length}');

    // 先检查是否存在进行中的考试
    ExamState? state = await getCurrentUserExamState(examId);

    if (state != null) {
      debugPrint('找到现有考试状态，状态: ${state.status}');
      debugPrint('现有状态答案数量: ${state.answers.length}');

      if (state.status == ExamStatus.inProgress) {
        // 更新现有状态 - 直接替换答案，不合并
        debugPrint('更新现有进行中的考试状态（直接替换答案）');
        state = ExamState(
          examId: examId,
          userId: currentUser.id,
          examTitle: state.examTitle,
          answers: Map<String, dynamic>.from(answers), // 直接使用新答案，不合并
          remainingSeconds: remainingSeconds,
          lastUpdated: DateTime.now(),
          status: ExamStatus.inProgress,
          lastActivity: DateTime.now(),
        );
        debugPrint('更新后答案数量: ${state.answers.length}');
      } else {
        debugPrint('⚠️ 考试状态不是进行中: ${state.status}');
        // 如果状态不是进行中，但我们仍在保存，说明可能是恢复的考试
        // 强制更新为进行中状态
        state = ExamState(
          examId: examId,
          userId: currentUser.id,
          examTitle: state.examTitle,
          answers: Map<String, dynamic>.from(answers), // 直接使用新答案
          remainingSeconds: remainingSeconds,
          lastUpdated: DateTime.now(),
          status: ExamStatus.inProgress,
          lastActivity: DateTime.now(),
        );
        debugPrint('强制更新为进行中状态，答案数量: ${state.answers.length}');
      }
    } else {
      debugPrint('⚠️ 未找到现有考试状态，这通常不应该发生');
      debugPrint('创建新的考试状态（应该避免这种情况）');

      // 创建新状态（其实不应该走到这里，因为应该先调用startExam）
      final exam = ExamService.getExamById(examId);
      final examTitle = exam?.title ?? '未知考试';

      state = ExamState(
        examId: examId,
        userId: currentUser.id,
        examTitle: examTitle,
        answers: Map<String, dynamic>.from(answers),
        remainingSeconds: remainingSeconds,
        lastUpdated: DateTime.now(),
        status: ExamStatus.inProgress,
        lastActivity: DateTime.now(),
      );
      debugPrint('新建状态答案数量: ${state.answers.length}');
    }

    final result = await saveExamState(state);
    debugPrint('保存考试状态结果: ${result ? '成功' : '失败'}');
    return result;
  }

  // 开始考试
  static Future<ExamState?> startExam(String examId, int durationInMinutes) async {
    final currentUser = UserData.currentUser;
    if (currentUser == null) {
      return null;
    }

    // 获取考试信息以获取标题
    final exam = ExamService.getExamById(examId);
    final examTitle = exam?.title ?? '未知考试';

    // 先检查是否已经完成过这个考试
    final result = await getCurrentUserExamResult(examId);
    if (result != null) {
      // 已经完成过考试，不能再次开始
      return null;
    }

    // 检查是否有进行中的考试
    final existingState = await getCurrentUserExamState(examId);
    if (existingState != null && existingState.status == ExamStatus.inProgress) {
      // 有进行中的考试，返回现有状态
      return existingState;
    }

    // 创建新的考试状态
    final state = ExamState.start(examId, currentUser.id, examTitle, durationInMinutes);
    final saved = await saveExamState(state);

    return saved ? state : null;
  }

  // 完成考试
  static Future<bool> completeExam(String examId, ExamResult result) async {
    final currentUser = UserData.currentUser;
    if (currentUser == null) {
      debugPrint('❌ 完成考试失败: 当前用户为空');
      return false;
    }

    debugPrint('=== ExamStateService.completeExam ===');
    debugPrint('考试ID: $examId');
    debugPrint('用户ID: ${currentUser.id}');

    try {
      // 获取考试信息
      final exam = ExamService.getExamById(examId);
      if (exam != null) {
        debugPrint('获取考试信息成功: ${exam.title}');
        // 使用 ExamService 评分客观题
        final objectiveScores = ExamService.gradeObjectiveQuestions(exam, result);

        // 计算总分
        int totalObjectiveScore = 0;
        objectiveScores.forEach((_, score) => totalObjectiveScore += score);

        debugPrint('客观题评分完成，总分: $totalObjectiveScore');

        // 更新结果中的分数
        result = result.updateObjectiveScores(objectiveScores, totalObjectiveScore);
      } else {
        debugPrint('⚠️ 获取考试信息失败，跳过评分');
      }

      // 保存考试结果
      debugPrint('正在保存考试结果...');
      final resultSaved = await saveExamResult(result);
      debugPrint('保存考试结果: ${resultSaved ? '成功' : '失败'}');

      // 删除进行中的考试状态
      debugPrint('正在删除考试状态...');
      debugPrint('删除参数: examId=$examId, userId=${currentUser.id}');

      final stateRemoved = await removeExamState(examId, currentUser.id);
      debugPrint('删除考试状态: ${stateRemoved ? '成功' : '失败'}');

      // 验证删除结果 - 再次检查状态是否真的被删除了
      debugPrint('验证删除结果...');
      final stateAfterDelete = await getExamState(examId, currentUser.id);
      if (stateAfterDelete != null) {
        debugPrint('❌ 警告: 删除后状态仍然存在!');
        debugPrint('   状态ID: ${stateAfterDelete.examId}');
        debugPrint('   状态用户: ${stateAfterDelete.userId}');
        debugPrint('   状态: ${stateAfterDelete.status}');

        // 尝试强制删除
        debugPrint('尝试强制删除...');
        final prefs = await SharedPreferences.getInstance();
        final key = _getExamStateKey(examId, currentUser.id);
        final forceRemoved = await prefs.remove(key);
        debugPrint('强制删除结果: ${forceRemoved ? '成功' : '失败'}');

        // 再次验证
        final finalCheck = await getExamState(examId, currentUser.id);
        debugPrint('最终验证: ${finalCheck == null ? '状态已删除' : '状态仍存在'}');
      } else {
        debugPrint('✅ 验证成功: 考试状态已被删除');
      }

      final overallSuccess = resultSaved && stateRemoved;
      debugPrint('考试完成流程: ${overallSuccess ? '✅ 成功' : '❌ 失败'}');

      return overallSuccess;
    } catch (e) {
      debugPrint('❌ 完成考试时出错: $e');

      // 即使出错，也尝试保存结果和删除状态
      debugPrint('尝试错误恢复...');
      final resultSaved = await saveExamResult(result);
      debugPrint('错误恢复 - 保存考试结果: ${resultSaved ? '成功' : '失败'}');

      final stateRemoved = await removeExamState(examId, currentUser.id);
      debugPrint('错误恢复 - 删除考试状态: ${stateRemoved ? '成功' : '失败'}');

      final overallSuccess = resultSaved && stateRemoved;
      debugPrint('错误恢复结果: ${overallSuccess ? '✅ 成功' : '❌ 失败'}');

      return overallSuccess;
    }
  }

  // 获取当前用户所有未完成的考试状态
  static Future<List<Map<String, dynamic>>> getIncompleteExams({String? excludeExamId}) async {
    final currentUser = UserData.currentUser;
    if (currentUser == null) {
      debugPrint('获取未完成考试失败: 当前用户为空');
      return [];
    }

    debugPrint('=== ExamStateService.getIncompleteExams ===');
    debugPrint('正在为用户 ${currentUser.id} (${currentUser.name}) 检查未完成考试...');
    debugPrint('当前时间: ${DateTime.now()}');
    if (excludeExamId != null) {
      debugPrint('排除当前考试: $excludeExamId');
    }

    try {
      final prefs = await SharedPreferences.getInstance();
      final allKeys = prefs.getKeys();
      final List<Map<String, dynamic>> incompleteExams = [];

      debugPrint('SharedPreferences中共有 ${allKeys.length} 个键');
      debugPrint('考试状态键前缀: $_examStateKeyPrefix');

      // 筛选出属于当前用户的考试状态键
      final userStateKeys = allKeys.where((key) =>
        key.startsWith(_examStateKeyPrefix) &&
        key.contains(currentUser.id)
      ).toList();

      debugPrint('找到 ${userStateKeys.length} 个考试状态键:');
      for (var key in userStateKeys) {
        debugPrint('  - $key');
      }

      // 检查是否有重复的考试ID
      final Map<String, List<String>> examIdToKeys = {};
      for (var key in userStateKeys) {
        // 从键中提取考试ID (格式: exam_state_examId_userId)
        final parts = key.split('_');
        if (parts.length >= 3) {
          final examId = parts[2]; // 假设考试ID在第3部分
          if (!examIdToKeys.containsKey(examId)) {
            examIdToKeys[examId] = [];
          }
          examIdToKeys[examId]!.add(key);
        }
      }

      // 检查重复的考试状态
      for (var entry in examIdToKeys.entries) {
        if (entry.value.length > 1) {
          debugPrint('⚠️ 发现重复的考试状态:');
          debugPrint('   考试ID: ${entry.key}');
          debugPrint('   重复的键: ${entry.value}');
          debugPrint('   这可能是导致重复提示的原因！');

          // 清理重复状态，只保留最新的一个
          await _cleanupDuplicateStates(entry.key, entry.value);
        }
      }

      if (userStateKeys.isEmpty) {
        debugPrint('❌ 没有找到任何考试状态键，可能的原因:');
        debugPrint('   1. 用户ID不匹配: ${currentUser.id}');
        debugPrint('   2. 考试状态没有保存');
        debugPrint('   3. 键名格式不正确');
        debugPrint('所有键列表:');
        for (var key in allKeys) {
          if (key.startsWith(_examStateKeyPrefix)) {
            debugPrint('   - $key');
          }
        }
      }
      
      // 获取每个未完成考试的详细信息
      for (final key in userStateKeys) {
        try {
          final String? stateJson = prefs.getString(key);
          if (stateJson != null) {
            debugPrint('📋 正在处理考试状态: $key');
            final Map<String, dynamic> stateMap = jsonDecode(stateJson);
            final ExamState state = ExamState.fromJson(stateMap);

            final lastUpdated = state.lastUpdated;
            final now = DateTime.now();
            final timeDifference = now.difference(lastUpdated);

            debugPrint('考试状态详情:');
            debugPrint('  - 考试ID: ${state.examId}');
            debugPrint('  - 用户ID: ${state.userId}');
            debugPrint('  - 状态: ${state.status}');
            debugPrint('  - 最后更新: ${state.lastUpdated}');
            debugPrint('  - 时间差: ${timeDifference.inMinutes}分钟 ${timeDifference.inSeconds % 60}秒');
            debugPrint('  - 剩余时间: ${state.remainingSeconds}秒');
            debugPrint('  - 答案数量: ${state.answers.length}');
            debugPrint('  - 包含活跃会话: ${state.answers.containsKey('_active_session')}');
            if (state.answers.containsKey('_active_session')) {
              debugPrint('  - 活跃会话值: ${state.answers['_active_session']}');
            }

            // 考虑任何未完成的考试状态
            if (state.status != ExamStatus.completed) {
              debugPrint('✅ 考试状态未完成，继续处理...');

              // 检查是否已经有对应的考试结果
              final existingResult = await getCurrentUserExamResult(state.examId);
              if (existingResult != null) {
                debugPrint('⚠️ 发现已完成的考试结果，但考试状态仍为未完成');
                debugPrint('   考试ID: ${state.examId}');
                debugPrint('   结果ID: ${existingResult.id}');
                debugPrint('   结果分数: ${existingResult.totalScore}');
                debugPrint('   这可能是状态清理失败导致的，跳过此考试状态');
                continue; // 跳过这个状态，因为考试实际上已经完成
              }

              // 对于有活动会话标记的考试状态，我们现在总是将其视为可恢复的
              // 这是因为如果应用被强制关闭，活动会话标记不会被清除
              // 而用户重新登录时应该有机会恢复考试
              if (state.answers.containsKey('_active_session') && state.answers['_active_session'] == true) {
                final lastUpdated = state.lastUpdated;
                final now = DateTime.now();
                final timeDifferenceMinutes = now.difference(lastUpdated).inMinutes;
                final timeDifferenceSeconds = now.difference(lastUpdated).inSeconds;

                debugPrint('🔍 发现活动会话: ${state.examId}');
                debugPrint('   最后更新: ${timeDifferenceMinutes}分钟前 (${timeDifferenceSeconds}秒前)');

                // 检查是否有最近活动时间戳
                if (state.lastActivity != null) {
                  final activityDifferenceMinutes = now.difference(state.lastActivity!).inMinutes;

                  debugPrint('   最后活动时间: ${activityDifferenceMinutes}分钟前');

                  // 如果最近5分钟内有活动，认为是当前正在进行的考试，跳过
                  if (activityDifferenceMinutes < 5) {
                    debugPrint('   ⏭️ 跳过当前正在进行的考试（最近5分钟内有活动）');
                    continue;
                  }
                }

                // 判断可能的场景
                if (timeDifferenceMinutes < 2) {
                  debugPrint('   场景: 应用切换或短暂中断');
                } else if (timeDifferenceMinutes < 30) {
                  debugPrint('   场景: 可能是应用被杀死或系统重启');
                } else {
                  debugPrint('   场景: 长时间中断，可能是系统关机重启');
                }

                debugPrint('✅ 将活动会话视为可恢复的未完成考试');

                // 不再跳过活动会话，而是将其视为未完成考试
                // 这样用户就可以选择恢复或重新开始
              } else {
                debugPrint('🔍 非活动会话的未完成考试: ${state.examId}');
              }
              
              // 获取考试详情
              final examId = state.examId;

              // 如果这是当前正在进行的考试，跳过它
              if (excludeExamId != null && examId == excludeExamId) {
                debugPrint('跳过当前正在进行的考试: $examId');
                continue;
              }

              debugPrint('正在获取考试详情: $examId');
              final exam = await ExamService.getExamById(examId);

              if (exam != null) {
                debugPrint('添加未完成考试: ${exam.title}');
                // 添加到未完成考试列表
                incompleteExams.add({
                  'examId': examId,
                  'examTitle': exam.title,
                  'remainingSeconds': state.remainingSeconds,
                  'lastUpdated': state.lastUpdated.toIso8601String(),
                  'answerCount': state.answers.length,
                  'totalQuestions': exam.questions.length,
                });
              } else {
                debugPrint('找不到考试详情: $examId');
              }
            } else {
              debugPrint('考试已完成，跳过: ${state.examId}');
            }
          }
        } catch (e) {
          debugPrint('处理考试状态出错: $key, 错误: $e');
          // 继续处理下一个键
          continue;
        }
      }
      
      // 按最后更新时间降序排序，最近的排在前面
      incompleteExams.sort((a, b) => 
        DateTime.parse(b['lastUpdated']).compareTo(DateTime.parse(a['lastUpdated']))
      );
      
      debugPrint('共找到 ${incompleteExams.length} 个未完成考试');
      return incompleteExams;
    } catch (e) {
      debugPrint('获取未完成考试失败: $e');
      return [];
    }
  }

  // 清理重复的考试状态，只保留最新的一个
  static Future<void> _cleanupDuplicateStates(String examId, List<String> duplicateKeys) async {
    try {
      debugPrint('开始清理重复状态...');
      final prefs = await SharedPreferences.getInstance();

      // 获取所有重复状态的详细信息
      final List<MapEntry<String, ExamState>> statesWithKeys = [];

      for (var key in duplicateKeys) {
        final stateJson = prefs.getString(key);
        if (stateJson != null) {
          try {
            final stateMap = jsonDecode(stateJson);
            final state = ExamState.fromJson(stateMap);
            statesWithKeys.add(MapEntry(key, state));
            debugPrint('   状态: $key, 最后更新: ${state.lastUpdated}');
          } catch (e) {
            debugPrint('   解析状态失败: $key, 错误: $e');
          }
        }
      }

      if (statesWithKeys.isEmpty) {
        debugPrint('没有有效的重复状态需要清理');
        return;
      }

      // 按最后更新时间排序，保留最新的一个
      statesWithKeys.sort((a, b) => b.value.lastUpdated.compareTo(a.value.lastUpdated));

      final latestEntry = statesWithKeys.first;
      debugPrint('保留最新状态: ${latestEntry.key}, 时间: ${latestEntry.value.lastUpdated}');

      // 删除其他重复的状态
      for (int i = 1; i < statesWithKeys.length; i++) {
        final entryToDelete = statesWithKeys[i];
        debugPrint('删除重复状态: ${entryToDelete.key}, 时间: ${entryToDelete.value.lastUpdated}');

        final deleted = await prefs.remove(entryToDelete.key);
        debugPrint('删除结果: ${deleted ? '成功' : '失败'}');
      }

      debugPrint('✅ 重复状态清理完成，保留了最新的状态');

    } catch (e) {
      debugPrint('❌ 清理重复状态失败: $e');
    }
  }

  // 清理特定用户的重复考试状态
  static Future<void> _cleanupDuplicateStatesForUser(String examId, String userId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final allKeys = prefs.getKeys();

      // 查找该用户该考试的所有状态键
      final userExamKeys = allKeys.where((key) =>
        key.startsWith(_examStateKeyPrefix) &&
        key.contains(examId) &&
        key.contains(userId)
      ).toList();

      if (userExamKeys.length <= 1) {
        // 没有重复状态
        return;
      }

      debugPrint('发现 ${userExamKeys.length} 个重复状态，准备清理');

      // 解析所有状态并按时间排序
      List<MapEntry<String, ExamState>> statesWithKeys = [];

      for (final key in userExamKeys) {
        try {
          final stateJson = prefs.getString(key);
          if (stateJson != null) {
            final stateMap = jsonDecode(stateJson);
            final state = ExamState.fromJson(stateMap);
            statesWithKeys.add(MapEntry(key, state));
          }
        } catch (e) {
          debugPrint('解析状态失败: $key, 错误: $e');
          // 删除无效的状态
          await prefs.remove(key);
        }
      }

      if (statesWithKeys.length <= 1) {
        return;
      }

      // 按最后更新时间排序，保留最新的一个
      statesWithKeys.sort((a, b) => b.value.lastUpdated.compareTo(a.value.lastUpdated));

      final latestEntry = statesWithKeys.first;
      debugPrint('保留最新状态: ${latestEntry.key}');

      // 删除其他重复的状态
      for (int i = 1; i < statesWithKeys.length; i++) {
        final entryToDelete = statesWithKeys[i];
        debugPrint('删除重复状态: ${entryToDelete.key}');
        await prefs.remove(entryToDelete.key);
      }

      debugPrint('✅ 用户重复状态清理完成');

    } catch (e) {
      debugPrint('❌ 清理用户重复状态失败: $e');
    }
  }
  
  // 恢复考试，可选择调整剩余时间
  static Future<ExamState?> resumeExam(String examId, {int? adjustedRemainingSeconds}) async {
    final currentUser = UserData.currentUser;
    if (currentUser == null) {
      debugPrint('❌ resumeExam: 当前用户为空');
      return null;
    }

    debugPrint('=== resumeExam ===');
    debugPrint('考试ID: $examId');
    debugPrint('用户ID: ${currentUser.id}');
    debugPrint('调整剩余时间: $adjustedRemainingSeconds 秒');

    // 获取现有考试状态
    ExamState? state = await getCurrentUserExamState(examId);

    if (state != null) {
      debugPrint('找到现有考试状态: ${state.status}');

      if (state.status == ExamStatus.inProgress) {
        debugPrint('考试状态为进行中，准备恢复');

        // 如果提供了调整后的时间，更新考试状态
        if (adjustedRemainingSeconds != null) {
          debugPrint('更新剩余时间: ${state.remainingSeconds} -> $adjustedRemainingSeconds');
          state = state.updateRemainingTime(adjustedRemainingSeconds);
        }

        // 确保状态被正确保存
        final saved = await saveExamState(state);
        debugPrint('恢复考试状态保存结果: ${saved ? '成功' : '失败'}');

        if (saved) {
          debugPrint('✅ 考试恢复成功');
          return state;
        } else {
          debugPrint('❌ 考试状态保存失败');
          return null;
        }
      } else {
        debugPrint('⚠️ 考试状态不是进行中: ${state.status}');
        return null;
      }
    } else {
      debugPrint('❌ 未找到考试状态');
      return null;
    }
  }

  // 获取指定考试的所有学生的结果（仅管理员使用）
  static Future<List<ExamResult>> getAllExamResults(String examId) async {
    try {
      final results = ExamService.getExamResults(examId);
      return results;
    } catch (e) {
      debugPrint('获取所有考试结果失败: $e');
      return [];
    }
  }

  // 原有方法保留，确保向后兼容
  static Future<List<ExamResult>> getAllStudentResultsForExam(String examId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      
      // 获取所有键
      final keys = prefs.getKeys();
      
      // 筛选出与该考试相关的结果键
      final resultKeys = keys.where((key) => 
        key.startsWith(_examResultKeyPrefix) && key.contains(examId)
      ).toList();
      
      // 获取每个键对应的结果
      final List<ExamResult> results = [];
      for (var key in resultKeys) {
        final String? resultJson = prefs.getString(key);
        if (resultJson != null) {
          try {
            final Map<String, dynamic> resultMap = jsonDecode(resultJson);
            results.add(ExamResult.fromJson(resultMap));
          } catch (e) {
            debugPrint('解析考试结果失败: $e');
          }
        }
      }
      
      return results;
    } catch (e) {
      debugPrint('获取所有学生考试结果失败: $e');
      return [];
    }
  }

  // 将考试结果导出为Excel文件
  static Future<String?> exportExamResultToExcel(ExamResult result, Exam exam, int durationInMinutes) async {
    try {
      // 尝试多个导出路径，找到可用的路径就使用
      // 新的路径结构：按试卷ID分组，然后按学生ID分组
      List<String> possiblePaths = [];

      // 使用originalId作为试卷ID（如果存在）
      String examId = exam.originalId ?? exam.id;
      // 如果还是有exam_前缀，移除它
      if (examId.startsWith('exam_')) {
        examId = examId.substring(5);
      }

      if (Platform.isAndroid) {
        // Android设备尝试两种路径，所有学生的答卷都保存在同一个试卷ID文件夹中
        possiblePaths.addAll([
          '/data/userdata/com.westone.examapp/result/$examId',
          '/storage/emulated/0/Android/data/com.example.examapp/files/result/$examId',
        ]);
      } else {
        // iOS设备使用应用文档目录，所有学生的答卷都保存在同一个试卷ID文件夹中
        final directory = await getApplicationDocumentsDirectory();
        possiblePaths.add('${directory.path}/ExamApp/result/$examId');
      }
      
      String? dirPath;
      
      // 尝试每个路径，找到第一个可以创建或已存在的路径
      for (String path in possiblePaths) {
        try {
          final dir = Directory(path);
          
          // 尝试创建目录
          if (!await dir.exists()) {
            await dir.create(recursive: true);
          }
          
          // 测试写入权限
          final testFile = File('$path/.test_write');
          await testFile.writeAsString('test');
          await testFile.delete();
          
          // 如果能成功创建目录和写入文件，使用这个路径
          dirPath = path;
          debugPrint('成功找到可用的导出路径: $dirPath');
          break;
        } catch (e) {
          debugPrint('路径不可用: $path, 错误: $e');
          continue;
        }
      }
      
      // 如果所有路径都不可用，回退到应用文档目录
      if (dirPath == null) {
        debugPrint('所有预设路径都不可用，回退到应用文档目录');
        final directory = await getApplicationDocumentsDirectory();
        dirPath = '${directory.path}/ExamApp/result/$examId';
        final dir = Directory(dirPath);
        if (!await dir.exists()) {
          await dir.create(recursive: true);
        }
      }
      
      // 文件名格式：用户账号_试卷id_考试用时（分钟）.xlsx
      final fileName = '${result.userId}_${examId}_${durationInMinutes}.xlsx';
      final filePath = '$dirPath/$fileName';
      
      // 创建Excel对象
      final excel = Excel.createExcel();
      final sheetName = excel.getDefaultSheet() ?? 'Sheet1';
      final sheet = excel.sheets[sheetName]!;
      
      // 添加表头（base64编码） - 简化版本只包含题目ID和学生答案
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 0))..value = _encodeToBase64('题目ID');
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 0))..value = _encodeToBase64('学生答案');
      
      // 添加数据（简化版本只包含题目ID和学生答案）
      int rowIndex = 1;
      for (var question in exam.questions) {
        // 题目ID（base64编码）
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: rowIndex))
          ..value = _encodeToBase64(question.id);

        // 学生答案（base64编码）
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: rowIndex))
          ..value = _getStudentAnswer(question.id, result.answers);

        rowIndex++;
      }
      
      // 保存Excel文件
      final fileBytes = excel.encode();
      if (fileBytes != null) {
        final file = File(filePath);
        await file.writeAsBytes(fileBytes);
        debugPrint('已导出考试结果到: $filePath');
        return filePath;
      }
      
      return null;
    } catch (e) {
      debugPrint('导出考试结果错误: $e');
      return null;
    }
  }
  
  // 将考试结果Excel文件和考试头像打包成zip文件
  static Future<String?> packageExamResultsToZip(ExamResult result, Exam exam, int durationInMinutes, String excelFilePath) async {
    try {
      // 如果Excel文件路径为空，先导出Excel文件
      String? finalExcelPath = excelFilePath;
      if (finalExcelPath == null || finalExcelPath.isEmpty) {
        finalExcelPath = await exportExamResultToExcel(result, exam, durationInMinutes);
        if (finalExcelPath == null) {
          debugPrint('导出Excel文件失败，无法打包成Zip');
          return null;
        }
      }
      
      // 使用originalId作为试卷ID（如果存在）
      String examId = exam.originalId ?? exam.id;
      // 如果还是有exam_前缀，移除它
      if (examId.startsWith('exam_')) {
        examId = examId.substring(5);
      }

      // 尝试多个导出路径，找到可用的路径就使用
      // 所有学生的ZIP文件都保存在同一个试卷ID文件夹中
      List<String> possiblePaths = [];

      if (Platform.isAndroid) {
        // Android设备尝试两种路径，所有学生的ZIP都保存在同一个试卷ID文件夹中
        possiblePaths.addAll([
          '/data/userdata/com.westone.examapp/result/$examId',
          '/storage/emulated/0/Android/data/com.example.examapp/files/result/$examId',
        ]);
      } else {
        // iOS设备使用应用文档目录，所有学生的ZIP都保存在同一个试卷ID文件夹中
        final directory = await getApplicationDocumentsDirectory();
        possiblePaths.add('${directory.path}/ExamApp/result/$examId');
      }
      
      String? dirPath;
      
      // 尝试每个路径，找到第一个可以创建或已存在的路径
      for (String path in possiblePaths) {
        try {
          final dir = Directory(path);
          
          // 尝试创建目录
          if (!await dir.exists()) {
            await dir.create(recursive: true);
          }
          
          // 测试写入权限
          final testFile = File('$path/.test_write');
          await testFile.writeAsString('test');
          await testFile.delete();
          
          // 如果能成功创建目录和写入文件，使用这个路径
          dirPath = path;
          debugPrint('ZIP打包成功找到可用路径: $dirPath');
          break;
        } catch (e) {
          debugPrint('ZIP打包路径不可用: $path, 错误: $e');
          continue;
        }
      }
      
      // 如果所有路径都不可用，回退到应用文档目录
      if (dirPath == null) {
        debugPrint('ZIP打包所有预设路径都不可用，回退到应用文档目录');
        final directory = await getApplicationDocumentsDirectory();
        dirPath = '${directory.path}/ExamApp/result/$examId';
        final dir = Directory(dirPath);
        if (!await dir.exists()) {
          await dir.create(recursive: true);
        }
      }
      
      // 创建ZIP文件名：用户账号_试卷id_考试用时（分钟）.zip
      final zipFileName = '${result.userId}_${examId}_${durationInMinutes}.zip';
      final zipFilePath = '$dirPath/$zipFileName';
      
      // 创建一个ZIP编码器
      final encoder = ZipFileEncoder();
      encoder.create(zipFilePath);
      debugPrint('🗜️ 开始创建ZIP文件: $zipFilePath');

      int addedFilesCount = 0;

      // 添加Excel文件到ZIP
      final excelFile = File(finalExcelPath);
      if (await excelFile.exists()) {
        encoder.addFile(excelFile);
        addedFilesCount++;
        debugPrint('✅ 已添加Excel文件到ZIP: $finalExcelPath');
      } else {
        debugPrint('❌ Excel文件不存在: $finalExcelPath');
      }

      // 添加学生头像照片到ZIP
      if (result.avatarPath != null && result.avatarPath!.isNotEmpty) {
        final avatarFile = File(result.avatarPath!);
        if (await avatarFile.exists()) {
          // 提取文件扩展名
          String extension = 'jpg';
          final pathParts = avatarFile.path.split('.');
          if (pathParts.length > 1) {
            extension = pathParts.last.toLowerCase();
          }
          // 创建在ZIP内的头像文件名
          final avatarFileName = '${result.userId}_头像.$extension';
          encoder.addFile(avatarFile, avatarFileName);
          addedFilesCount++;
          debugPrint('✅ 已添加学生头像照片到ZIP: ${avatarFile.path} -> $avatarFileName');
        } else {
          debugPrint('❌ 学生头像文件不存在: ${result.avatarPath}');
        }
      } else {
        debugPrint('ℹ️ 学生没有头像照片');
      }
      
      // 创建题目ID到序号的映射
      final Map<String, int> questionIndexMap = {};
      for (int index = 0; index < exam.questions.length; index++) {
        questionIndexMap[exam.questions[index].id] = index + 1; // 序号从1开始
      }

      // 添加答题照片到ZIP
      debugPrint('📸 开始处理答题照片，共有 ${result.answerImages.length} 个题目有照片');

      for (var entry in result.answerImages.entries) {
        final questionId = entry.key;
        final imagePaths = entry.value;

        debugPrint('📸 处理题目 $questionId 的照片，共 ${imagePaths.length} 张');

        for (int i = 0; i < imagePaths.length; i++) {
          final imagePath = imagePaths[i];
          final imageFile = File(imagePath);

          debugPrint('📸 检查照片文件: $imagePath');

          if (await imageFile.exists()) {
            // 提取文件扩展名，如果无法提取则默认为jpg
            String extension = 'jpg';
            final pathParts = imageFile.path.split('.');
            if (pathParts.length > 1) {
              extension = pathParts.last.toLowerCase();
            }

            // 生成时间戳（毫秒级）
            final timestamp = DateTime.now().millisecondsSinceEpoch;

            // 创建在ZIP内的照片文件名：学生账号_题目ID_时间戳_序号.扩展名
            final imageFileName = '${result.userId}_${questionId}_${timestamp}_${i+1}.$extension';
            encoder.addFile(imageFile, imageFileName);
            addedFilesCount++;
            debugPrint('✅ 已添加答题照片到ZIP: $imagePath -> $imageFileName');
          } else {
            debugPrint('❌ 答题照片文件不存在: $imagePath');
          }
        }
      }

      if (result.answerImages.isEmpty) {
        debugPrint('ℹ️ 该学生没有答题照片');
      }
      
      // 关闭ZIP文件
      encoder.close();

      debugPrint('🎉 已成功创建ZIP文件: $zipFilePath');
      debugPrint('📊 ZIP文件包含 $addedFilesCount 个文件');

      // 验证ZIP文件是否创建成功
      final zipFile = File(zipFilePath);
      if (await zipFile.exists()) {
        final fileSize = await zipFile.length();
        debugPrint('✅ ZIP文件验证成功，大小: ${fileSize} 字节');
        return zipFilePath;
      } else {
        debugPrint('❌ ZIP文件创建失败，文件不存在');
        return null;
      }
    } catch (e) {
      debugPrint('打包ZIP文件错误: $e');
      return null;
    }
  }
  
  // 获取题目类型名称
  static String _getQuestionTypeName(QuestionType type) {
    switch (type) {
      case QuestionType.singleChoice:
        return '单选题';
      case QuestionType.multipleChoice:
        return '多选题';
      case QuestionType.fillBlank:
        return '填空题';
      case QuestionType.trueOrFalse:
        return '判断题';
      case QuestionType.shortAnswer:
        return '简答题';
      default:
        return '未知类型';
    }
  }
  
  // 获取题目选项
  static String _getQuestionOptions(Question question) {
    if (question is SingleChoiceQuestion || question is MultipleChoiceQuestion) {
      List<Choice> choices = [];
      if (question is SingleChoiceQuestion) {
        choices = question.choices;
      } else if (question is MultipleChoiceQuestion) {
        choices = question.choices;
      }
      
      return choices.map((option) => '${option.id}: ${option.text}').join('\n');
    }
    
    return '';
  }
  
  // 获取正确答案（管理员版本）
  static String _getCorrectAnswer(Question question) {
    if (question is SingleChoiceQuestion) {
      if (question.correctOption >= 0 && question.correctOption < question.choices.length) {
        return question.choices[question.correctOption].id;
      }
      return '';
    } else if (question is MultipleChoiceQuestion) {
      return question.correctOptions.map((index) {
        if (index >= 0 && index < question.choices.length) {
          return question.choices[index].id;
        }
        return '';
      }).join(', ');
    } else if (question is FillBlankQuestion) {
      return question.correctAnswer;
    } else if (question is TrueOrFalseQuestion) {
      return question.correctAnswer ? '正确' : '错误';
    } else if (question is ShortAnswerQuestion) {
      return question.referencedAnswer ?? '';
    }
    
    return '';
  }

  // 获取正确答案（考生版本 - 密文）
  static String _getCorrectAnswerForStudent(Question question) {
    // 对所有题型都返回密文，保护答案不被泄露
    return '***';
  }

  // 管理员专用：导出考试结果到Excel（显示明文答案）
  static Future<String?> exportExamResultToExcelForAdmin(ExamResult result, Exam exam, int durationInMinutes) async {
    try {
      // 使用originalId作为试卷ID（如果存在）
      String examId = exam.originalId ?? exam.id;
      // 如果还是有exam_前缀，移除它
      if (examId.startsWith('exam_')) {
        examId = examId.substring(5);
      }

      // 尝试多个导出路径，找到可用的路径就使用
      // 管理员版本所有学生的答卷都保存在同一个试卷ID文件夹中
      List<String> possiblePaths = [];

      if (Platform.isAndroid) {
        // Android设备尝试两种路径，所有学生的答卷都保存在同一个试卷ID文件夹中
        possiblePaths.addAll([
          '/data/userdata/com.westone.examapp/admin_result/$examId',
          '/storage/emulated/0/Android/data/com.example.examapp/files/admin_result/$examId',
        ]);
      } else {
        // iOS设备使用应用文档目录，所有学生的答卷都保存在同一个试卷ID文件夹中
        final directory = await getApplicationDocumentsDirectory();
        possiblePaths.add('${directory.path}/ExamApp/admin_result/$examId');
      }
      
      String? dirPath;
      
      // 尝试每个路径，找到第一个可以创建或已存在的路径
      for (String path in possiblePaths) {
        try {
          final dir = Directory(path);
          
          // 尝试创建目录
          if (!await dir.exists()) {
            await dir.create(recursive: true);
          }
          
          // 测试写入权限
          final testFile = File('$path/.test_write');
          await testFile.writeAsString('test');
          await testFile.delete();
          
          // 如果能成功创建目录和写入文件，使用这个路径
          dirPath = path;
          debugPrint('管理员Excel成功找到可用路径: $dirPath');
          break;
        } catch (e) {
          debugPrint('管理员Excel路径不可用: $path, 错误: $e');
          continue;
        }
      }
      
      // 如果所有路径都不可用，回退到应用文档目录
      if (dirPath == null) {
        debugPrint('管理员Excel所有预设路径都不可用，回退到应用文档目录');
        final directory = await getApplicationDocumentsDirectory();
        dirPath = '${directory.path}/ExamApp/admin_result/$examId';
        final dir = Directory(dirPath);
        if (!await dir.exists()) {
          await dir.create(recursive: true);
        }
      }
      
      // 文件名格式：admin_用户账号_试卷id_考试用时（分钟）.xlsx
      final fileName = 'admin_${result.userId}_${examId}_${durationInMinutes}.xlsx';
      final filePath = '$dirPath/$fileName';
      
      // 创建Excel对象
      final excel = Excel.createExcel();
      final sheetName = excel.getDefaultSheet() ?? 'Sheet1';
      final sheet = excel.sheets[sheetName]!;
      
      // 添加表头（base64编码）
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 0))..value = _encodeToBase64('题目id');
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 0))..value = _encodeToBase64('题目内容');
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 0))..value = _encodeToBase64('题目类型');
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 3, rowIndex: 0))..value = _encodeToBase64('题目选项');
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 4, rowIndex: 0))..value = _encodeToBase64('参考答案');
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 5, rowIndex: 0))..value = _encodeToBase64('学生答案');
      
      // 添加数据（所有内容base64编码）
      int rowIndex = 1;
      for (var question in exam.questions) {
        // 题目ID（base64编码）
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: rowIndex))
          ..value = _encodeToBase64(question.id);

        // 题目内容（base64编码）
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: rowIndex))
          ..value = _encodeToBase64(question.text);

        // 题目类型（base64编码）
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: rowIndex))
          ..value = _encodeToBase64(_getQuestionTypeName(question.type));

        // 题目选项（base64编码）
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 3, rowIndex: rowIndex))
          ..value = _encodeToBase64(_getQuestionOptions(question));

        // 参考答案（base64编码） - 管理员版本显示明文
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 4, rowIndex: rowIndex))
          ..value = _encodeToBase64(_getCorrectAnswer(question));

        // 学生答案（base64编码）
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 5, rowIndex: rowIndex))
          ..value = _getStudentAnswer(question.id, result.answers);

        rowIndex++;
      }
      
      // 保存Excel文件
      final fileBytes = excel.encode();
      if (fileBytes != null) {
        final file = File(filePath);
        await file.writeAsBytes(fileBytes);
        debugPrint('已导出管理员考试结果到: $filePath');
        return filePath;
      }
      
      return null;
    } catch (e) {
      debugPrint('导出管理员考试结果错误: $e');
      return null;
    }
  }
  
  // 通用base64编码方法
  static String _encodeToBase64(String content) {
    // 如果内容为空，返回空字符串
    if (content.isEmpty) {
      return '';
    }

    // 将内容转换为base64格式
    try {
      final bytes = utf8.encode(content);
      return base64.encode(bytes);
    } catch (e) {
      debugPrint('Base64编码失败: $e');
      return content; // 如果编码失败，返回原始文本
    }
  }

  // 获取学生答案（base64编码）
  static String _getStudentAnswer(String questionId, Map<String, dynamic> answers) {
    if (!answers.containsKey(questionId)) {
      return '';
    }

    dynamic answer = answers[questionId];
    String answerText = '';

    if (answer is String) {
      answerText = answer;
    } else if (answer is bool) {
      answerText = answer ? '正确' : '错误';
    } else if (answer is List) {
      // 处理多空填空题的答案列表
      List<String> answerList = answer.map((item) {
        String itemStr = item?.toString() ?? '';
        // 如果答案为空，用空格代替
        return itemStr.trim().isEmpty ? ' ' : itemStr.trim();
      }).toList();
      answerText = answerList.join(',');

      debugPrint('多空填空答案处理: 题目=$questionId');
      debugPrint('  原始答案: $answer');
      debugPrint('  处理后答案: $answerText');
    } else {
      answerText = answer.toString();
    }

    // 使用通用编码方法
    return _encodeToBase64(answerText);
  }
} 